<?php

namespace App\Wxaccount\Controllers;


use App\Store\Models\Member\Member;
use App\Store\Models\Wxapp\WxaccountSetting;
use EasyWeChat\OfficialAccount\Application;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Store\Models\Account\Account;
use Illuminate\Support\Facades\Validator;


class WxAuthController extends Controller
{
    /**
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     * @throws \Illuminate\Validation\ValidationException
     */
    public function accountAuth(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'account_name' => 'required',
            'password' => 'required',
            'wx_open_id' => 'required',
            'cp_id' => 'sometimes',

        ], [
            'account_name.required' => '账号必填',
            'password.required' => '密码必填',
            'wx_open_id.required' => 'openid不能为空',
            'cp_id.sometimes' => 'cpid不能为空',
        ]);


        if ($validator->fails()) {
            $msg = $validator->errors()->first();
            return response()->json(['code' => '001', 'msg' => $msg]);
        }
        $params = $validator->validated();

        $cp_id =$params['cp_id']?? 0;

        if($cp_id>0){
            $info = Account::query()
                ->where('account_name', $params['account_name'])
                ->where('cp_id', $params['cp_id'])
                ->orderby('id', 'desc')
                ->first();
        }else{
            $info = Account::query()
                ->where('account_name', $params['account_name'])
                ->orderby('id', 'desc')
                ->first();
        }

        if (!empty($info)) {
            if ($info->is_del != 1) {
                return response()->json(['code' => '001', 'msg' => '该账号已被删除']);
            }
            if ($info->status != 1) {
                return response()->json(['code' => '001', 'msg' => '账号已被禁用']);
            }
            if ($info->password != MD5($params['password'])) {
                return response()->json(['code' => '001', 'msg' => '帐号或者密码错误']);
            }

            $data['wx_account_openid'] = $params['wx_open_id'];
            Account::query()
                ->where('account_name', $params['account_name'])
                ->update($data);
            return response()->json(['code' => '00', 'msg' => '验证成功']);
        } else {
            return response()->json(['code' => '001', 'msg' => '帐号或者密码错误']);
        }
    }



    /**
     * 获取openid
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse|mixed|string
     * @throws \EasyWeChat\Kernel\Exceptions\InvalidArgumentException
     * @throws \Illuminate\Validation\ValidationException
     */
    public function getOpenId(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'wxacc_code' => 'required',
            'cp_id' => 'sometimes',
        ], [
            'wxacc_code.required' => 'code不能为空',
        ]);

        if ($validator->fails()) {
            $msg = $validator->errors()->first();
            return response()->json(['code' => '001', 'msg' => $msg]);
        }
        $params = $validator->validated();


        $cp_id =$params['cp_id']?? 0;

        if($cp_id>0){
            $setting = WxaccountSetting::query()
                ->where('cp_id', $params['cp_id'])->first();
            if (!$setting) {
                return response()->json(['code' => '001', 'msg' => '公众号配置信息不存在']);
            }
        }else{
            $setting = WxaccountSetting::query()->where(['appid' => config('wx.wx_defult_appid')])->first();
        }


        $config = [
            'app_id' => $setting->appid,
            'secret' => $setting->appsecret,
        ];

        $wxapp = new Application($config);
        $accessToken = $wxapp->getAccessToken();
        $token = $accessToken->getToken();
        $res = file_get_contents('https://api.weixin.qq.com/sns/oauth2/access_token?access_token=' . $token . '&appid=' . $setting->appid . '&secret=' . $setting->appsecret . '&code=' . $params['wxacc_code'] . '&grant_type=authorization_code');
        $auth = json_decode($res, true);
        info('根据code获取openid', $auth);
        $openid ='';
        if (!empty($auth)) {
            $openid = $auth['openid'] ?? '';
            $unionid = $auth['unionid']?? '';
            if(!empty($unionid)){
                $meminfo=Member::query()->where(['wx_unionid'=>$res['unionid'],'is_del'=>1])->first();
                if($meminfo){
                    Member::query()->where(['wx_unionid'=>$res['unionid'],'is_del'=>1])->update(['wx_account_open_id'=>$openid]);
                }
            }
        }

        if(empty($openid)){
            return response()->json(['code' => '001', 'msg' => '公众号授权失败']);
        }
        $data['openid'] = $openid;

        return response()->json(['code' => '000', 'msg' => '获取横杠','data'=>$data]);
    }




}
